package net.bracode.view;

import java.util.List;

import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TableView;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import net.bracode.dao.Database;
import net.bracode.entity.Participante;

public class ParticipanteShow extends Application {
	
	private MenuPrincipal menu;
	private TableView<Participante> table;
	private List<Participante> participantes;
	private AnchorPane pane;
	private Scene scene;
	private Stage stage;
	private Button voltar;
	
	
	public ParticipanteShow(MenuPrincipal menu) {
		this.menu = menu;
		participantes = Database.getDatabase().find();
	}
	
	@Override
	public void start(Stage stage) throws Exception {
		iniciarComponentes();
		this.stage = stage;
		
		pane.getChildren().addAll(table, voltar);
		
		iniciarListeners();
		
		scene.getStylesheets().add("login.css");
		stage.setScene(scene);
		stage.setTitle("Todos os Participantes");
		stage.show();
		iniciarLayouts();
	}
	
	private void iniciarComponentes(){ 	
		pane = new AnchorPane();
		scene = new Scene(pane, 600, 400);
		voltar = new Button("Menu Principal");
		table = new TableView<Participante>();
		table.getColumns().addAll(Participante.getColumns(table));
		table.setItems(getParticipantes());
	}
	
	private void iniciarLayouts(){
		table.setLayoutY(40);
		voltar.setLayoutX((pane.getWidth() - voltar.getWidth()) / 2);
		voltar.setLayoutY(10);
	}
	
	private void iniciarListeners(){
		
		voltar.setOnAction(new EventHandler<ActionEvent>() {
			@Override
			public void handle(ActionEvent arg0) {
				voltar();
			}
		});
		
		table.getSelectionModel().selectedItemProperty().addListener(
				new ChangeListener<Participante>() {

					@Override
					public void changed(
							ObservableValue<? extends Participante> arg0,
							Participante arg1, Participante arg2) {
						
						try {
							new ParticipanteDetails(arg2, ParticipanteShow.this)
									.start(getStage());
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
					
				});
	}
	
	public Stage getStage() {
		return stage;
	}
	
	public ObservableList<Participante> getParticipantes(){
		ObservableList<Participante> data = FXCollections.observableArrayList();
		data.addAll(this.participantes);
	
		return data;
	}
	
	private void voltar(){
		try {
			this.menu.start(getStage());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
